<template>
  <div class="data-view-config">
    <!-- Trigger Button -->
    <div class="toolbar">
      <!-- <el-button type="primary" :icon="Search" @click="open = true">
        高级筛选/分组/排序
      </el-button> -->
    </div>

    <!-- Right Drawer Panel -->
    <el-drawer
      v-model="open"
      direction="rtl"
      size="520px"
      :with-header="false"
      custom-class="drawer--fancy"
    >
      <div class="drawer-header">
        <div class="title">
          <el-icon><Setting /></el-icon>
          数据视图配置
        </div>
        <div class="actions">
          <el-button type="text" @click="resetAll">重置</el-button>
          <el-button type="primary" @click="applyAll">应用</el-button>
        </div>
      </div>

      <el-tabs v-model="tab" stretch class="tabs--fancy">
        <!-- 筛选 Tab -->
        <el-tab-pane label="筛选条件" name="filter">
          <div class="panel">
            <div class="panel-hint">添加字段筛选，支持 AND / OR 逻辑组合</div>
            <div class="conditions">
              <transition-group name="list" tag="div">
                <div v-for="(c, idx) in filters" :key="c.id" class="condition-row">
                  <!-- 字段选择 -->
                  <el-select
                    v-model="c.field"
                    placeholder="字段"
                    size="small"
                    class="cond-field"
                    clearable
                  >
                    <el-option v-for="f in fields" :key="f.key" :label="f.label" :value="f.key" />
                  </el-select>

                  <!-- 操作符 -->
                  <el-select v-model="c.operator" placeholder="操作" size="small" class="cond-op">
                    <el-option
                      v-for="op in operators"
                      :key="op.value"
                      :label="op.label"
                      :value="op.value"
                    />
                  </el-select>

                  <!-- 值输入（动态组件） -->
                  <component
                    :is="valueComponent(c.field)"
                    v-model="c.value"
                    :placeholder="getPlaceholder(c.operator)"
                    size="small"
                    class="cond-val"
                    v-bind="getInputProps(c.field)"
                  />

                  <!-- 逻辑连接符（AND/OR） -->
                  <el-select
                    v-model="c.join"
                    placeholder="逻辑"
                    size="small"
                    class="cond-join"
                    v-if="idx < filters.length - 1"
                  >
                    <el-option label="且 (AND)" value="and" />
                    <el-option label="或 (OR)" value="or" />
                  </el-select>

                  <!-- 删除按钮 -->
                  <el-button type="danger" size="small" circle @click="removeCondition(idx)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </transition-group>

              <!-- 添加条件按钮 -->
              <div class="cond-tools">
                <el-button type="primary" size="small" @click="addCondition">
                  <el-icon><Plus /></el-icon>
                  添加条件
                </el-button>

                <!-- 筛选范围 -->
                <el-switch
                  v-model="filterScopeGlobal"
                  inline-prompt
                  active-text="全表"
                  inactive-text="当前页"
                  size="small"
                />
              </div>
            </div>

            <!-- 筛选预览 -->
            <el-collapse v-model="collapseFilterExtras" class="extras">
              <el-collapse-item title="筛选预览" name="1">
                <div class="preview">{{ previewText }}</div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-tab-pane>

        <!-- 排序 Tab -->
        <el-tab-pane label="排序设置" name="sort">
          <div class="panel">
            <div class="panel-hint">拖拽调整优先级，支持多字段排序</div>
            <draggable v-model="sorts" item-key="field" class="sort-list" handle=".drag-handle">
              <template #item="{ element, index }">
                <div class="sort-row">
                  <!-- 拖拽手柄 -->
                  <el-icon class="drag-handle"><Rank /></el-icon>

                  <!-- 字段选择 -->
                  <el-select
                    v-model="element.field"
                    placeholder="选择字段"
                    size="small"
                    class="sort-field"
                  >
                    <el-option v-for="f in fields" :key="f.key" :label="f.label" :value="f.key" />
                  </el-select>

                  <!-- 排序方向 -->
                  <el-button-group size="small">
                    <el-button
                      :type="element.order === 'asc' ? 'primary' : 'default'"
                      @click="element.order = 'asc'"
                    >
                      <el-icon><CaretTop /></el-icon>升序
                    </el-button>
                    <el-button
                      :type="element.order === 'desc' ? 'primary' : 'default'"
                      @click="element.order = 'desc'"
                    >
                      <el-icon><CaretBottom /></el-icon>降序
                    </el-button>
                  </el-button-group>

                  <!-- 删除排序 -->
                  <el-button type="danger" size="small" circle @click="sorts.splice(index, 1)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </template>
            </draggable>

            <!-- 添加排序 -->
            <el-button type="primary" size="small" @click="addSort">
              <el-icon><Plus /></el-icon>
              添加排序
            </el-button>
          </div>
        </el-tab-pane>

        <!-- 分组 Tab -->
        <el-tab-pane label="分组统计" name="group">
          <div class="panel">
            <div class="panel-hint">选择分组字段，并为数值字段添加统计</div>

            <!-- 分组字段选择 -->
            <el-select
              v-model="groupFields"
              multiple
              placeholder="选择分组字段"
              size="small"
              style="width: 100%; margin-bottom: 12px"
            >
              <el-option v-for="f in fields" :key="f.key" :label="f.label" :value="f.key" />
            </el-select>

            <!-- 统计设置 -->
            <div class="stat-settings">
              <div v-for="(s, idx) in groupStats" :key="s.id" class="stat-row">
                <!-- 数值字段 -->
                <el-select v-model="s.field" placeholder="数值字段" size="small">
                  <el-option
                    v-for="f in numericFields"
                    :key="f.key"
                    :label="f.label"
                    :value="f.key"
                  />
                </el-select>

                <!-- 统计函数 -->
                <el-select v-model="s.func" placeholder="函数" size="small">
                  <el-option label="求和" value="sum" />
                  <el-option label="平均值" value="avg" />
                  <el-option label="计数" value="count" />
                  <el-option label="最大值" value="max" />
                  <el-option label="最小值" value="min" />
                </el-select>

                <!-- 删除统计 -->
                <el-button type="danger" size="small" circle @click="groupStats.splice(idx, 1)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>

              <!-- 添加统计 -->
              <el-button type="primary" size="small" @click="addStat">
                <el-icon><Plus /></el-icon>
                添加统计
              </el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 抽屉底部 -->
      <div class="drawer-footer">
        <el-checkbox v-model="showAggregates" size="small"> 显示分组小计 </el-checkbox>
        <div class="footer-actions">
          <el-button size="small" @click="open = false">关闭</el-button>
          <el-button type="primary" size="small" @click="applyAll"> 应用配置 </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, shallowRef } from 'vue';
import { ElMessage, ElButton, ElIcon } from 'element-plus';
import draggable from 'vuedraggable';
import {
  Plus,
  Delete,
  Search,
  Setting,
  Rank,
  CaretTop,
  CaretBottom
} from '@element-plus/icons-vue';
// ====== 1. 状态定义 ======
// 字段元数据（真实项目中应来自后端或配置）
const fields = [
  { key: 'customer', label: '客户名称', type: 'string' },
  { key: 'orderNo', label: '订单号', type: 'string' },
  { key: 'amount', label: '金额', type: 'number' },
  { key: 'status', label: '状态', type: 'string' },
  { key: 'createdAt', label: '创建时间', type: 'date' }
];

// 主状态
const open = ref(false);
const tab = ref('filter');
const filters = reactive<FilterCondition[]>([]);
const sorts = reactive<SortCondition[]>([]);
const groupFields = ref<string[]>([]);
const groupStats = reactive<StatCondition[]>([]);
const showAggregates = ref(true);
const filterScopeGlobal = ref(true);
const collapseFilterExtras = ref(['1']);

// 保存的视图
const savedViews = shallowRef<SavedView[]>([{ id: 'v1', name: '大客户订单' }]);
const activeView = ref<string | null>(null);

// ====== 2. 类型定义 ======
interface FilterCondition {
  id: string;
  field: string | null;
  operator: string;
  value: any;
  join: 'and' | 'or';
}

interface SortCondition {
  field: string | null;
  order: 'asc' | 'desc';
}

interface StatCondition {
  id: string;
  field: string | null;
  func: 'sum' | 'avg' | 'count' | 'max' | 'min';
}

interface SavedView {
  id: string;
  name: string;
}

// ====== 3. 工具函数 ======
const uid = () => Date.now() + Math.random().toString(36).slice(2, 8);

// 获取值输入组件
const valueComponent = (fieldKey: any) => {
  const field = fields.find((f) => f.key === fieldKey);
  if (!field) return 'el-input';
  if (field.type === 'number') return 'el-input-number';
  if (field.type === 'date') return 'el-date-picker';
  return 'el-input';
};

// 获取输入组件的额外属性
const getInputProps = (fieldKey: any) => {
  const field = fields.find((f) => f.key === fieldKey);
  if (field?.type === 'number') {
    return { precision: 2, controls: false };
  }
  if (field?.type === 'date') {
    return { type: 'date', format: 'YYYY-MM-DD', valueFormat: 'YYYY-MM-DD' };
  }
  return {};
};

// 获取操作符的占位符
const getPlaceholder = (operator: string) => {
  const map: Record<string, string> = {
    contains: '请输入包含的内容',
    eq: '请输入精确值',
    neq: '请输入排除的值',
    gt: '请输入最小值',
    lt: '请输入最大值',
    between: '请选择范围'
  };
  return map[operator] || '请输入值';
};

// ====== 4. 操作方法 ======
const addCondition = () => {
  filters.push({
    id: uid(),
    field: null,
    operator: 'contains',
    value: null,
    join: 'and'
  });
};

const removeCondition = (i: number) => {
  filters.splice(i, 1);
};

const operators = [
  { label: '包含', value: 'contains' },
  { label: '等于', value: 'eq' },
  { label: '不等于', value: 'neq' },
  { label: '大于', value: 'gt' },
  { label: '小于', value: 'lt' },
  { label: '介于', value: 'between' }
];

const addSort = () => {
  sorts.push({ field: null, order: 'desc' });
};

const addStat = () => {
  groupStats.push({ id: uid(), field: null, func: 'sum' });
};

const numericFields = computed(() => fields.filter((f) => f.type === 'number'));

const previewText = computed(() => {
  if (!filters.length) return '未设置筛选条件';
  return filters
    .map((c, i) => {
      let val = String(c.value || '空值');
      if (Array.isArray(c.value)) {
        val = c.value.join(' ~ ');
      }
      return `${c.field ? getFieldLabel(c.field) : '字段'} ${getOperatorLabel(c.operator)} ${val}${
        i < filters.length - 1 ? ` ${c.join === 'and' ? '且' : '或'} ` : ''
      }`;
    })
    .join(' ');
});

// 辅助函数：获取字段标签
const getFieldLabel = (key: string) => {
  return fields.find((f) => f.key === key)?.label || key;
};

// 辅助函数：获取操作符标签
const getOperatorLabel = (value: string) => {
  return operators.find((o) => o.value === value)?.label || value;
};

// 应用配置
const applyAll = () => {
  const payload = {
    filters: JSON.parse(JSON.stringify(filters)),
    sorts: JSON.parse(JSON.stringify(sorts)),
    group: {
      fields: [...groupFields.value],
      stats: JSON.parse(JSON.stringify(groupStats)),
      showAggregates: showAggregates.value
    },
    scope: filterScopeGlobal.value ? 'global' : 'page'
  };
  ElMessage.success('配置已应用');
  open.value = false; // 应用后自动关闭
};

// 重置所有
const resetAll = () => {
  filters.splice(0, filters.length);
  sorts.splice(0, sorts.length);
  groupFields.value = [];
  groupStats.splice(0, groupStats.length);
  showAggregates.value = true;
  filterScopeGlobal.value = true;
  ElMessage.info('已重置');
};
</script>

<style lang="scss" scoped>
.data-view-config {
  s .toolbar {
    display: flex;
    align-items: center;

    .view-select {
      width: 200px;
    }
  }

  .drawer--fancy {
    background: linear-gradient(180deg, #ffffff, #f9f9ff);
    box-shadow: -20px 0 40px rgba(0, 0, 0, 0.08);
    border-left: 1px solid rgba(0, 0, 0, 0.05);
    backdrop-filter: blur(10px);
  }

  .drawer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 0 20px 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.08);
    background: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(10px);
  }

  .title {
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .actions {
    display: flex;
    gap: 8px;
  }

  .tabs--fancy {
    :deep(.el-tabs__header) {
      padding-left: 12px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.08);
    }

    :deep(.el-tabs__item) {
      font-weight: 500;
      color: #666;
      &.is-active {
        color: #409eff;
        font-weight: 600;
      }
    }
  }

  .panel {
    padding: 16px 20px;
  }

  .panel-hint {
    color: #777;
    font-size: 13px;
    margin-bottom: 12px;
    line-height: 1.4;
  }

  .condition-row {
    display: flex;
    gap: 8px;
    align-items: center;
    margin-bottom: 10px;
    padding: 10px;
    border-radius: 8px;
    background: #ffffff;
    border: 1px solid #e8e8e8;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    transition: all 0.2s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      transform: translateY(-1px);
    }
  }

  .cond-field {
    width: 150px;
  }
  .cond-op {
    width: 100px;
  }
  .cond-val {
    flex: 1;
  }
  .cond-join {
    width: 90px;
  }

  .cond-tools {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 8px;
  }

  .extras {
    margin-top: 12px;
  }

  .preview {
    padding: 10px;
    border-radius: 6px;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    font-family: 'Monaco', 'Consolas', monospace;
    font-size: 12px;
    color: #495057;
    line-height: 1.4;
  }

  .sort-list {
    margin-bottom: 12px;
  }

  .sort-row {
    display: flex;
    gap: 8px;
    align-items: center;
    padding: 10px;
    border-radius: 8px;
    background: #ffffff;
    border: 1px solid #e8e8e8;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    margin-bottom: 8px;
    transition: all 0.2s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    }
  }

  .drag-handle {
    cursor: grab;
    color: #999;
    font-size: 16px;
    opacity: 0.7;
    transition: all 0.2s ease;

    &:hover {
      color: #409eff;
      opacity: 1;
    }
  }

  .sort-field {
    width: 200px;
  }

  .stat-settings {
    margin-top: 12px;
  }

  .stat-row {
    display: flex;
    gap: 8px;
    align-items: center;
    margin-bottom: 8px;
  }

  .drawer-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px 22px;
    border-top: 1px solid rgba(0, 0, 0, 0.08);
    background: rgba(255, 255, 255, 0.8);
  }

  .footer-actions {
    display: flex;
    gap: 8px;
  }

  /* 微动效 */
  .list-enter-active,
  .list-leave-active {
    transition: all 0.22s ease;
  }
  .list-enter-from {
    opacity: 0;
    transform: translateY(-6px) scale(0.99);
  }
  .list-leave-to {
    opacity: 0;
    transform: translateY(-6px) scale(0.99);
  }
}
</style>
